<template>
  <div class="parameter-product">
    <div class="flex justify-center mb-6">
      <span class="text-xl font-bold text-gray-800">采购入库({{rute.query.taskCode}})</span>
    </div>
    <hr />
    <div class="rute-info">
      <span>到货单号:{{rute.query.arrivalCode}}</span>
      <span>采购订单号:{{rute.query.purchaseCode}}</span>
      <span>供应商:{{rute.query.supplier}}</span><br />
      <span>卸货库区:A区<!--模拟数据--></span>
      <span>到货日期:{{rute.query.arrivalDate}}</span>
    </div>
    <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column type="index" prop="serial" label="序号" />
      <el-table-column prop="gs1" label="GS1编码" />
      <el-table-column prop="batchNum" label="批次号" />
      <el-table-column prop="category" label="物料类别" />
      <el-table-column prop="productCode" label="物料编码" />
      <el-table-column prop="productName" label="物料名称" />
      <el-table-column prop="spec" label="物料规格" />
      <el-table-column prop="unit" label="计量单位" />
      <el-table-column label="待入库量" :formatter="formatPendingStock" />
      <el-table-column prop="areaId" label="收货库区*" width="100px">
        <template #default="scope">
          <el-select v-model="scope.row.areaId" placeholder="库区" style="width: 75px" >
            <el-option v-for="area in areaList" :key="area.areaId" :label="area.areaName" :value="area.areaId" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="productDate" label="生产日期" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <span class="clickable text-warning" @click="handleTaskDetail(scope.row)">删除</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper" :total="totalCount" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <div style="margin-top: 20px; text-align: center;">
      <el-button type="primary" @click="handleBatchInsert">提交入库</el-button>
    </div>
    <!-- 可扩展弹窗等功能 -->
    <!-- <StockSettingDialog v-model="dialogVisible" :current-row="currentRow" @on-save="handleSaveSuccess" /> -->
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { queryDetail, insert, deleteById } from '@/api/stockIn/purchaseStockIn.js'
import {queryArea} from '@/api/stockIn/stockInQuery.js'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'

// 分页相关参数
const page = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const tableData = ref([])
const selectedRows = ref([])

const rute = useRoute()
const router = useRouter()
//声明调用接口查询的库区列表
const areaList=ref([])
// 加载状态
const loading = ref(false)

let insertParams=[];
async function init() {
  try { 
    // 显示加载状态
    loading.value = true
    // 使用对象扩展运算符简化参数构建
    let params = {
      a_type: 'purchase',
      page: 1,
      pageSize: 10,
      pd: {
        gs1: '',
        batchNum: '',
        category: '', 
        productCode: '',
        productName: '',
        spec: '',
        unit: '',
        inNum: '',
        productDate: '',
        taskId:Number(rute.query.taskId)
       }
      
    }
    const res = await queryDetail(params)
    console.log(params)
    if (res.code === 200) {
      tableData.value = res.data.list
      console.log(res.data.list)
      totalCount.value = res.data.total
    } else {
      console.error('获取数据失败:', res)
      // 可以在这里添加错误提示
      // ElMessage.error(`获取数据失败: ${res.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('接口请求错误:', error)
    // ElMessage.error('网络错误，请稍后重试')
  } finally {
    // 无论成功失败都关闭加载状态
    loading.value = false
  }
}

// 获取库区列表数据
const getAreaList = async () => {
  try {
    // 调用接口获取数据
    const response = await queryArea();
    console.log(response);
    // 假设接口返回格式为 { data: [{ id: 1, name: 'A区' }, ...] }
    areaList.value = response.data;
    console.log('库区列表:', areaList.value);
  } catch (error) {
    console.error('获取库区列表失败', error);
    ElMessage.error('获取库区列表失败，请稍后重试');
  }
};

onMounted(() => {
  init(),
  getAreaList()
})

 function formatPendingStock(row) {
    // 确保数值存在，避免 NaN
    const inNum = Number(row.inNum) || 0;
    const arrivalNum = Number(row.arrivalNum) || 0;
    return arrivalNum - inNum;
  }
const handleSizeChange = newSize => {
  pageSize.value = newSize
  page.value = 1
  init()
}
const handleCurrentChange = newPage => {
  page.value = newPage
  init()
}

const handleTaskDetail = row => {
  console.log('删除本行：', row)
  // 可跳转详情页或弹窗
  ElMessageBox.confirm('确定要删除此入库记录吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await deleteById(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功！')
          // 刷新列表
          init()
        } else {
          ElMessage.error(res.msg || '删除失败！')
        }
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('网络错误，删除失败！')
      }
    })
    .catch(() => {
      // 用户取消操作，不做任何处理
      console.log('用户取消了删除操作')
    })
}

function handleSelectionChange(rows) {
  selectedRows.value = rows
  console.log('当前选择的行:', selectedRows.value)  

  insertParams = rows.map(row => ({
  areaId: row.areaId,  
  availableNum: row.inNum, // 遍历每个row取对应值
  batchNo: row.batchNum,
  batchId: row.batchId,
  createBy: 101, // 假设创建人ID为101
  expireDate: '', //到期时间
  freezeStock: 0, //冻结数量
  mid: row.mid,
  productDate: row.productDate,
  stock: row.arrivalNum-row.inNum,
  stockId: row.ckid, //仓库ID，假设为1
  productCode: row.productCode,
  did:row.did,
}));
}

async function handleBatchInsert() {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择要入库的数据！')
    return
  }
  try {
    await ElMessageBox.confirm('确定要提交选中的数据进行入库吗？', '确认入库', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    // 批量插入，假设后端支持数组批量插入
    console.log('批量入库参数:', insertParams)
    const res = await insert(insertParams)
    if (res.code === 200) {
      ElMessage.success('批量入库成功！')
      router.push({ 
        name: 'purchase1'
      })
    } else {
      ElMessage.error(res.msg || '批量入库失败！')
    }
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('网络错误，批量入库失败！')
      console.error(e)
    }
    // 用户取消弹窗不提示错误
  }
}
</script>

<style scoped>
.clickable {
  cursor: pointer;
  color: #409eff;
}
.demo-pagination-block {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  margin: 20px 0;
}
.search-container {
  margin: 5px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
.search-form {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.form-actions {
  display: flex;
  align-items: center;
}
.rute-info {
  margin: 15px 0;
  font-size: 14px;
  color: #666;
}
.rute-info span {
  margin-right: 20px;
}
</style>